package com.amanda.reggie.service.impl;

import com.amanda.reggie.common.BaseContext;
import com.amanda.reggie.entity.AddressBook;
import com.amanda.reggie.mapper.AddressBookMapper;
import com.amanda.reggie.service.AddressBookService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author amanda
 * @Description 地址簿业务实现
 */
@Slf4j
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 获取用户全部地址
     */
    @Override
    public List<AddressBook> listAll(AddressBook addressBook) {
        // 1、获取当前登录用户id
        addressBook.setUserId(BaseContext.getCurrentId());
        // 2、条件构造器
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        // SQL:select * from address_book where user_id = ? order by update_time desc
        return addressBookService.list(queryWrapper);
    }

    /**
     * 设置当前地址为默认地址
     */
    @Override
    public AddressBook setDefault(AddressBook addressBook) {
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        wrapper.set(AddressBook::getIsDefault, 0);
        // 1、设置全部地址都不是默认，SQL:update address_book set is_default = 0 where user_id = ?
        addressBookService.update(wrapper);
        addressBook.setIsDefault(1);
        // 2、后单独设置，SQL:update address_book set is_default = 1 where id = ?
        addressBookService.updateById(addressBook);
        return addressBook;
    }
}
